<template>
  <div class="index">
    <NavBar/>
    <div class="container">
      <div class="w73 ans-l">
        <!-- 大咖推荐 -->
        <div class="recom">
          <div class="recom-h item">
              <span class="icon icon-recom"></span>
              <b class="ftz16">大咖推荐</b>
              <router-link to="/qa/allmasters" class="fr">全部大咖</router-link>
          </div>
          <div class="recom-c">
            <swiper :options="swiperBannerOption" ref="mySwiper">
              <swiper-slide v-for="(item, index) in masterList" :key="index" class="item">
                <router-link :to="'/dashboard/qa/' + item.sysUserFieldTagVO.userId">
                  <div class="photo">
                    <div class="photo-img photo-level">
                      <img :src="item.sysUserFieldTagVO.avatar">
                      <span :class="[`level`,`level_${item.sysUserFieldTagVO.authType}`,`mini`]"></span>
                    </div>
                    <img v-if="item.certificated" src="../../assets/res/img/icon_appr.png" class="appr">
                  </div>
                  <div class="name ftz16">{{item.sysUserFieldTagVO.authName}}</div>
                  <div class="tip">
                      擅长：{{item.sysUserFieldTagVO.field}}
                      <p>回答数：{{item.sysUserFieldTagVO.answerCount ? item.sysUserFieldTagVO.answerCount : 0}}</p>
                  </div>
                  <div class="brief">
                      {{item.certification.descs}}
                  </div>
                  <div class="rec-btn">
                      <button id="sub_btn"
                        v-if="item.userFocus" class="black"
                        @mouseout="showCancleBtn(item, index, false)"
                        @mouseover="showCancleBtn(item, index, true)"
                        @click.stop.prevent="focus(index, item)">
                        {{!item.cancleBtn ? '已关注':'取消关注'}}
                      </button>
                      <button id="sub_btn" v-else @click.stop.prevent="focus(index, item)">+关注</button>
                      <button @click.stop.prevent="showQuestionBox(item)" v-if="!item.sysUserFieldTagVO.answerPay">免费提问</button>
                      <button @click.stop.prevent="showQuestionBox(item)" v-else><span class="icon-coin-white"></span>{{parseFloat(item.sysUserFieldTagVO.answerPay)}}提问</button>
                  </div>
                </router-link>
              </swiper-slide>
            </swiper>
            <div class="indi" id="rec_indi">
              <span class="icon icon-left"></span>
              <span class="icon icon-right"></span>
            </div>
          </div>
        </div>
        <!-- 问答专场 -->
        <div class="lot">
          <div class="lot-h item">
            <span class="icon icon-lot"></span>
            <b class="ftz16">问答专场</b>
            <div class="category-nav fr">
              <swiper :options="swiperCategoryOption" ref="mySwiper">
                <!-- slides -->
                <swiper-slide v-for="(item, index) in categoryList" :key="index">
                  <a  class="category-nav-item ftz16"
                    @click="selectCategory(index, item.id)"
                    :class="{'selected': index === currentCategoryIndex}">
                    {{item.name}}
                  </a>
                </swiper-slide>
              </swiper>
            </div>
            <span class="icon icon-left-category"></span>
            <span class="icon icon-right-category"></span>
          </div>
          <!-- 问题列表 -->
          <div class="all-lis-box" v-if="qaListDataArr.length > 0">
            <div class="lot-c item">
              <QuestionItem v-if="qaListDataArr[currentCategoryIndex].list.length" :list="qaListDataArr[currentCategoryIndex].list" @closeFn="closeQuestionBox"/>
              <button v-if="qaListDataArr[currentCategoryIndex].total > qaListDataArr[currentCategoryIndex].list.length"
                class="load-more-btns ftz16"
                @click="loadMore">
              <template v-if="qaListDataArr[currentCategoryIndex].isLoadingMore">
                <i class='layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop ftz20'></i>
                <span>正在加载，请稍候......</span>
              </template>
              <span v-else>点击加载更多...</span>
              </button>
            </div>
          </div>

        </div>
      </div>
      <div class="w23 fr ans-r">
        <!-- 我要提问 -->
        <div class="quiz"><router-link to="/qa/allmasters"><img src="../../assets/res/img/quiz.png"></router-link></div>
        <!-- 周回答排行 -->
        <div class="ans-rank item">
          <div class="item-h">
              <span class="line"></span>
              <b class="ftz16">周回答排行榜</b>
          </div>
          <div class="ans-rank-c">
            <ul>
              <li v-for="(item, index) in recordList" :key="index">
                <div class="photo">
                    <router-link :to="'/dashboard/qa/' + item.sysUserFieldTagVO.userId" class="photo-img photo-level">
                      <img :src="item.sysUserFieldTagVO.avatar">
                      <span :class="[`level`,`level_${item.sysUserFieldTagVO.authType}`,`mini`]"></span>
                    </router-link>
                    <img v-if="item.certificated" src="../../assets/res/img/icon_appr.png" class="appr">
                </div>
                <div class="info">
                    <router-link :to="'/dashboard/qa/' + item.sysUserFieldTagVO.userId" class="name ftz16">{{item.sysUserFieldTagVO.authName}}</router-link>
                    <span class="tip">本周回答<i>{{item.sysUserFieldTagVO.answerCount ? item.sysUserFieldTagVO.answerCount : 0}}</i>个问题</span>
                </div>
                <button @click="showQuestionBox(item)" class="quiz-btn">提问</button>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <!-- 提问弹窗 -->
      <transition name="fade">
        <QuestionBox v-show="questionBoxFlag"
        @closeFn="closeQuestionBox"
        @submitFn="submitQuestion"
        :masterInfo="targetMasterInfo"/>
      </transition>
      <!-- <Agreement v-if="showAgreementFlag"/> -->
    </div>
    <Footer/>
  </div>
</template>

<script type="text/ecmascript-6">
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import NavBar from '@/components/nav-bar'
import Footer from '@/components/footer'
import QuestionBox from '@/components/questionAnswer/question-box'
import QuestionItem from '@/components/questionAnswer/question-item'
import Agreement from '@/components/agreement/agreement'
import {
  getQuestionCategory,
  getRecommendMaster,
  getQuestionAnswerList,
  questionRecord,
  modifyUserFocus
} from '@/service/api'
export default {
  components: {
    swiper,
    swiperSlide,
    NavBar,
    Footer,
    QuestionBox,
    QuestionItem,
    Agreement
  },
  computed: {
    userId () {
      return this.$store.state.me.sysUser.userId
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.showLoadingModal()
      this.initDataList()
    })
  },
  data () {
    return {
      showAgreementFlag: false,
      questionBoxFlag: false,
      // 选中提问的大咖
      targetMasterInfo: {
        id: '',
        name: '',
        avatar: '',
        comment: '',
        field: '',
        answerCount: '',
        answerPay: ''
      },
      masterList: [],
      qaListDataArr: [],
      searchDataArr: [],
      qaList: [],
      qaListTotal: 0,
      isLoadingMore: false, // 正在加载更多
      recordList: [],
      // 推荐大咖 轮播设置
      swiperBannerOption: {
        slidesPerView: 4,
        spaceBetween: 30,
        slidesPerGroup: 3,
        loop: false,
        loopFillGroupWithBlank: true,
        navigation: {
          nextEl: '.icon-right',
          prevEl: '.icon-left'
        }
      },
      // 分类 轮播设置
      swiperCategoryOption: {
        slidesPerView: 'auto',
        spaceBetween: 40,
        loop: false,
        loopFillGroupWithBlank: true,
        navigation: {
          nextEl: '.icon-right-category',
          prevEl: '.icon-left-category'
        }
      },
      categoryList: [{id: 1, name: '最新问答'}, {id: 2, name: '精彩问答'}],
      currentCategoryIndex: 0,
      // 问题列表查询参数
      searchData: {
        sort: '', // 最新和精彩使用该字段。  最新：'', // 精彩：'read'
        field: '', // 其他分类问题使用该字段。
        pageSize: 5,
        pageNum: 1
      },
      layerLoad: null,
      // 排行榜列表查询参数
      recordSearchData: {
        pageSize: 5,
        pageNum: 1
      }
    }
  },
  methods: {
    showLoadingModal () {
      if (window.layer) {
        this.layerLoad = window.layer.load(0, {
          shade: false
        })
      }
    },
    closeLoadingModal () {
      if (window.layer) {
        window.layer.close(this.layerLoad)
      }
    },
    /**
     * 初始化页面数据，多个ajax同时请求
     */
    initDataList () {
      this.searchData.pageNum = 1
      Promise.all([
        this.getRecommendMasterList(),
        this.getQuestionCategoryList(),
        this.getQAList(),
        this.getRecordList()
      ]).then((res) => {
        this.closeLoadingModal()
        // 推荐大咖
        let masterData = res[0]
        if (masterData.status === 200) {
          this.masterList = masterData.data.list
        }
        // 问答分类
        let categoryData = res[1]
        if (categoryData.status === 200) {
          this.categoryList.push(...categoryData.data)
          this.initSearchArr() // 初始化数据数组和搜索条件数组
        }
        // 问答列表
        let qaData = res[2]
        this.qaListDataArr[this.currentCategoryIndex].list = []
        if (qaData.status === 200) {
          this.qaListDataArr[this.currentCategoryIndex].loaded = true
          this.qaListDataArr[this.currentCategoryIndex].total = qaData.data.total
          this.qaListDataArr[this.currentCategoryIndex].list = qaData.data.list
        }

        // 排行
        let recordData = res[3]
        if (recordData.status === 200) {
          this.recordList = recordData.data.list
        }
      }).catch((e) => {
        console.log(e)
      })
    },
    // 推荐大咖
    async getRecommendMasterList () {
      let list = await getRecommendMaster({})
      return list
    },
    // 分类
    async getQuestionCategoryList () {
      let list = await getQuestionCategory({classify: 'field'})
      return list
    },
    // 问答列表
    async getQAList () {
      let searchObj = this.searchDataArr[this.currentCategoryIndex]
      if (!searchObj) {
        searchObj = this.searchData
      }
      let list = await getQuestionAnswerList(searchObj)
      return list
    },
    // 问答排行列表
    async getRecordList () {
      let list = await questionRecord(this.recordSearchData)
      return list
    },
    /**
     * 初始化多个数据数组，和搜索条件数组
     */
    initSearchArr () {
      let searchData
      for (let i = 0; i < this.categoryList.length; i++) {
        if (i === 0) {
          searchData = {
            sort: '', // 最新和精彩使用该字段。  最新：'', // 精彩：'read'
            field: '', // 其他分类问题使用该字段。
            pageSize: 5,
            pageNum: 1
          }
        } else if (i === 1) {
          searchData = {
            sort: 'read', // 最新和精彩使用该字段。  最新：'', // 精彩：'read'
            field: '', // 其他分类问题使用该字段。
            pageSize: 5,
            pageNum: 1
          }
        } else {
          searchData = {
            sort: '', // 最新和精彩使用该字段。  最新：'', // 精彩：'read'
            fieldId: this.categoryList[i].id, // 其他分类问题使用该字段。
            pageSize: 5,
            pageNum: 1
          }
        }
        this.searchDataArr.push(searchData)

        this.qaListDataArr.push({
          total: 0,
          list: [],
          isLoadingMore: false,
          loaded: false
        })
      }
    },

    loadMore () {
      let index = this.currentCategoryIndex
      this.qaListDataArr[index].isLoadingMore = true
      this.searchDataArr[index].pageNum++
      this.getQAList().then((res) => {
        if (res.data) {
          this.qaListDataArr[index].list.push(...res.data.list)
        } else {
          this.searchDataArr[index].pageNum--
          window.layui.layer.msg('数据加载失败，请重新加载')
        }
        this.qaListDataArr[index].isLoadingMore = false
      })
    },
    showCancleBtn (item, index, flag) {
      let newItem = {...item}
      newItem.cancleBtn = flag
      this.$set(this.masterList, index, newItem)
    },
    cancleFollowed (id) {
      console.log(id)
    },
    // 关注
    async focus (itemIndex, item) {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再关注！')
        return false
      }
      let flag = item.userFocus ? '1' : '0'
      await modifyUserFocus({
        focusUserId: item.sysUserFieldTagVO.userId,
        focusStatus: flag
      })
      if (!item.userFocus) {
        item.userFocus = { focusStatus: 1 }
      } else {
        item.userFocus = null
      }
      this.$set(this.masterList, itemIndex, item)
    },

    // 问题分类切换
    selectCategory (index, id) {
      this.currentCategoryIndex = index
      if (!this.qaListDataArr[this.currentCategoryIndex].loaded) {
        this.doSearch()
      }
    },
    doSearch () {
      this.showLoadingModal()
      if (!this.qaListDataArr[this.currentCategoryIndex].loaded) {
        this.getQAList().then((res) => {
          this.closeLoadingModal()
          if (res.status === 200) {
            this.qaListDataArr[this.currentCategoryIndex].loaded = true
            this.qaListDataArr[this.currentCategoryIndex].list.push(...res.data.list)
            this.qaListDataArr[this.currentCategoryIndex].total = res.data.total
          }
        })
      }
    },
    // 显示提问弹窗
    showQuestionBox (item) {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再提问！')
        return false
      }
      if (this.userId === item.sysUserFieldTagVO.userId) {
        window.layui.layer.msg('不能向自己提问！')
        return false
      }
      this.questionBoxFlag = true
      let answerPay = item.sysUserFieldTagVO.answerPay
      if (!answerPay) {
        answerPay = 0
      }
      this.targetMasterInfo = {
        id: item.sysUserFieldTagVO.userId,
        name: item.sysUserFieldTagVO.authName,
        avatar: item.sysUserFieldTagVO.avatar,
        comment: item.sysUserFieldTagVO.comment,
        field: item.sysUserFieldTagVO.field,
        fieldId: item.sysUserFieldTagVO.fieldId,
        answerCount: item.sysUserFieldTagVO.answerCount | 0,
        answerPay: answerPay
      }
    },
    // 关闭提问弹窗
    closeQuestionBox () {
      this.questionBoxFlag = false
      console.log(123123)
      this.initDataList()
    },
    // 提交问题
    submitQuestion () {
      this.questionBoxFlag = false
      console.log('ok')
    }
  }
}
</script>

<style scoped lang="scss">
@import '../../style/res/questionlist.scss';
.container{
  min-height: auto;
}
.recom-c{
  .swiper-container {
    width: 100%;
    height: 100%;
  }
  .swiper-slide {
    position: relative;
    background: #fff;
    height: 270px;
    width: 208px;
    margin-top: 46px;
    box-sizing: border-box;
  }
}
.lot{
  .swiper-container {
    width: 100%;
    height: 100%;
  }
  .swiper-slide {
    position: relative;
    background: #fff;
    height: 48px;
    width: auto!important;
    box-sizing: border-box;
    a {
      display: block;
      height: 100%;
      position: relative;
      &::after {
        position: absolute;
        content:'';
        height: 4px;
        left:0;
        right: 0;
        bottom: 0;
        background-color: #fff;
        transition: none;
      }
      &.selected, &:hover {
        color: #f23e3e;
        &::after {
          background-color: #f23e3e;
        }
      }
    }
  }
}
.fade-enter-active, .fade-leave-active {
  transition: opacity .2s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>
